package com.bosssoft.springboot.demo1.config;

import com.bosssoft.springboot.demo1.exception.GlobalException;
import com.bosssoft.springboot.demo1.util.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Slf4j
@Configuration
@MapperScan("com.bosssoft.springboot.demo1.**.dao")    // Spring不知道dao在哪里 这里进行手动扫描
public class MybatisConfig {
    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory()  {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setTypeAliasesPackage("com.bosssoft.springboot.demo1.entity");    // 扫描Model

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            sessionFactory.setMapperLocations(resolver.getResources("classpath:**/mapper/*.xml"));    // 扫描映射文件

        } catch (IOException e) {
            log.info(e.getMessage(),e);
            throw new GlobalException(ResultCode.DATA_READ_ERROR,e);
        }

        try {
            return sessionFactory.getObject();
        } catch (Exception e) {
            log.info(e.getMessage(),e);
            throw new GlobalException(ResultCode.DATA_READ_ERROR,e);
        }
    }
}